package com.boyi.cycling_master.ui;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.boyi.cycling_master.R;
import com.boyi.cycling_master.application.CyclingApplication;
import com.boyi.cycling_master.bean.LoginResponseBean;
import com.boyi.cycling_master.common.MoT;
import com.boyi.cycling_master.common.PostParams;
import com.boyi.cycling_master.common.SnackUtil;
import com.boyi.cycling_master.main.user.PersonCenterPresenter;
import com.boyi.cycling_master.main.user.PersonCenterView;
import com.boyi.cycling_master.ui.base.BaseActivity;
import com.boyi.cycling_master.ui.base.BaseMvpActivity;
import com.bumptech.glide.Glide;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.mikhaellopez.circularimageview.CircularImageView;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
import com.zhy.autolayout.AutoFrameLayout;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Lee_Mofeel
 * @version 1.0
 * @date 2017/7/26/026 10:20
 * @Description 个人中心界面
 */

public class PersonCenterActivity extends BaseMvpActivity<PersonCenterView, PersonCenterPresenter> implements PersonCenterView,OnDateSetListener {
    @BindView(R.id.iv_user_img)
    CircularImageView ivUserImg;
    @BindView(R.id.iv_take_photo)
    ImageView ivTakePhoto;
    @BindView(R.id.iv_person_center_setting)
    ImageView ivPersonCenterSetting;
    @BindView(R.id.tv_person_center_level_value)
    TextView tvPersonCenterLevelValue;
    @BindView(R.id.pb_person_center_level)
    ProgressBar pbPersonCenterLevel;
    @BindView(R.id.tv_person_center_xin_name)
    TextView tvPersonCenterXinName;
    @BindView(R.id.tv_person_center_user_name)
    TextView tvPersonCenterUserName;
    @BindView(R.id.frame_user_name)
    AutoFrameLayout frameUserName;
    @BindView(R.id.tv_person_center_user_birthday)
    TextView tvPersonCenterUserBirthday;
    @BindView(R.id.frame_user_birthday)
    AutoFrameLayout frameUserBirthday;
    @BindView(R.id.tv_person_center_user_sex)
    TextView tvPersonCenterUserSex;
    @BindView(R.id.frame_user_sex)
    AutoFrameLayout frameUserSex;
    @BindView(R.id.tv_person_center_user_address)
    TextView tvPersonCenterUserAddress;
    @BindView(R.id.frame_user_address)
    AutoFrameLayout frameUserAddress;
    @BindView(R.id.frame_user_device)
    AutoFrameLayout frameUserDevice;
    private LoginResponseBean.DataCollectionBean userInfo;
    private AlertView alertViewSex;
    private TimePickerDialog mDialogYearMonthDay;
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    private ImageLoader imageLoader;
    private ImgSelConfig config;
    private String portrait;
    private String userNick;

    @Override
    public int getContentViewId() {
        return R.layout.activity_person_center;
    }

    @Override
    public void initLogic() {
        /* 根据当前数据库中是否存在用户 有则进行数据填写 */
        userInfo = CyclingApplication.getInstance().getUserInfo();
        if (userInfo == null)
            return;
        tvPersonCenterUserName.setText(userInfo.getUserNick());
        Glide.with(this).load(userInfo.getUserHead()).into(ivUserImg);
        tvPersonCenterXinName.setText(userInfo.getShowId());
        tvPersonCenterUserBirthday.setText(userInfo.getUserBirthday());
        tvPersonCenterUserSex.setText(userInfo.getUserSex().equals("0")  ? "男" : "女");
        tvPersonCenterUserAddress.setText(userInfo.getUserAddress());
        mDialogYearMonthDay = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setThemeColor(getResources().getColor(R.color.colorLoginBack))
                .setToolBarTextColor(Color.parseColor("#2586ff"))
                .setTitleStringId("生日")
                .setMaxMillseconds(System.currentTimeMillis())
                .setMinMillseconds(System.currentTimeMillis()-3155692597470L)
                .setCallBack(this)
                .setWheelItemTextSize(16)
                .build();
        initGrallery();
    }

    @Override
    public void getBundleExtras(Bundle bundle) {

    }


    @OnClick({R.id.iv_user_img, R.id.iv_take_photo, R.id.iv_person_center_setting, R.id.frame_user_name, R.id.frame_user_birthday, R.id.frame_user_sex, R.id.frame_user_address, R.id.frame_user_device})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_user_img:
                ImgSelActivity.startActivity(this, config, 2000);
                break;
            case R.id.iv_take_photo:
                break;
            case R.id.iv_person_center_setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.frame_user_name:
                startActivity(new Intent(this,ChangeUserNickActivity.class));
                break;
            case R.id.frame_user_birthday:
                mDialogYearMonthDay.show(getSupportFragmentManager(),"year_month_day");
                break;
            case R.id.frame_user_sex:
                showAlertSex();
                break;
            case R.id.frame_user_address:
                break;
            case R.id.frame_user_device:
                break;
        }
    }

    @Override
    public void showSnack(CharSequence chars) {
       MoT.showShort(this,chars);
    }


    @Override
    public void showSnack(int code) {

    }

    /**
     * 当修改信息成功以后
     * @param textView 修改后显示的TextView
     * @param updateInfo 修改后显示的信息
     * @param infoKey 修改信息的类型
     */
    @Override
    public void changeUserInfoSuccess(TextView textView, String updateInfo,String infoKey) {
        textView.setText(updateInfo);
        switch (infoKey){
            case "userSex":
                userInfo.setUserSex(updateInfo.equals("男") ? "0" : "1");
                break;
            case "userBirthday":
                userInfo.setUserBirthday(updateInfo);
                break;
            case "userAddress":
                break;
        }
        userInfo.save();
    }

    @Override
    public PersonCenterPresenter initPresenter() {
        return new PersonCenterPresenter();
    }

    /**
     * 日期选择回调
     * @param timePickerView
     * @param millseconds 选择的mills 需要将mills 转变为对应格式
     */
    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        String date = sf.format(new Date(millseconds));
        // 将日期提交到服务器
        presenter.changeUserInfo(tvPersonCenterUserBirthday,"userBirthday",date);
    }

    /**
     * 呈现性别选择alertView
     */
    public void showAlertSex(){
        alertViewSex = new AlertView("性别", null, null, null, new String[]{"男", "女"}, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (Integer.parseInt(userInfo.getUserSex()) != position) {// 注意下标问题
                    presenter.changeUserInfo(tvPersonCenterUserSex, "userSex", position == 1 ? "女" : "男");
                }
            }
        }).setCancelable(true).setOnDismissListener(null);
        alertViewSex.show();
    }

    /**
     * 初始化图片选择界面
     */
    private void initGrallery() {
        // 自定义图片加载器
        imageLoader = new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                // TODO 在这边可以自定义图片加载库来加载ImageView，例如Glide、Picasso、ImageLoader等
                Glide.with(context).load(path).into(imageView);
            }
        };
        // 自由配置选项
        config = new ImgSelConfig.Builder(this, imageLoader)
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.GRAY)
                // “确定”按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material)
                // 标题
                .title("图片")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(Color.parseColor("#3F51B5"))
                // 裁剪大小。needCrop为true的时候配置
                .cropSize(1, 1, 200, 200)
                .needCrop(true)
                // 第一个是否显示相机，默认true
                .needCamera(false)
                // 最大选择图片数量，默认9
                .maxNum(9)
                .build();
    }

    /**
     * 结果返回回调
     * @param requestCode 请求code
     * @param resultCode  返回code
     * @param data 数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片选择结果回调
        if (requestCode == 2000 && resultCode == RESULT_OK && data != null) {
            /* 可以选择多张 这里模式为单选  */
            List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
            for (String path : pathList) {
                // 得到图片
                //Log.d("GralleryDebug", path);
                // 将图片进行二进制Base64加密
                portrait = PostParams.fileToBase64String(path);
                // 显示当前选择的图片
                Glide.with(this).load(new File(path)).into(ivUserImg);
                // 将图片上传到服务器
                presenter.changeUserImg(portrait);
            }
        }
    }

}
